/*
 * Copyright 2013 Rodrigo Villablanca <villa061004@gmail.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cl.rvillablanca.jpatch.core;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class is responsible to copy all files on destination path.
 *
 * @author Rodrigo Villablanca <villa061004@gmail.com>
 */
public class Copier {

    private static final Logger LOGGER = Logger.getLogger(Copier.class.getName());
    private Path destination;
    private Path working;

    /**
     * Destination setter.
     *
     * @param destination Destination path.
     */
    public void setDestination(Path destination) {
        this.destination = destination;
    }

    /**
     * Working setter.
     *
     * @param working Working path.
     */
    public void setWorking(Path working) {
        this.working = working;
    }

    /**
     * Copy the files to destination path
     */
    public void copyAllFiles(List<Path> paths) throws IOException {
        for (Path p : paths) {
            copyFile(p);
        }
    }

    public void copyFile(Path p) throws IOException {
        Path copy = null, parent = null;
        LOGGER.log(Level.CONFIG, "{0} will be copied to {1}", new Object[]{p, destination});
        parent = p.getParent();
        if (parent != null) {
            LOGGER.log(Level.CONFIG, "Parent: {0}", parent);
            LOGGER.config("Creating parent on destination");
            Files.createDirectories(destination.resolve(parent));
        }
        copy = Files.copy(working.resolve(p), destination.resolve(p));
        LOGGER.log(Level.CONFIG, "{0} was copied", copy);
    }
}
